package com.zmj.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局过滤器配置
 * 若配置多个过滤器类，请勿采用继承OncePerRequestFilter实现
 *
 * @author zmj
 * @date 2021-08-30 09:58
 */

@Slf4j
@WebFilter(urlPatterns = "/*")
@ConditionalOnProperty(value = "special.filter-enabled", havingValue = "true")
@Component
public class CustomizeFilter extends OncePerRequestFilter {

    //获取请求对象handler
    @Resource
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        //判断是否有GetMapping注解
//        try {
//            HandlerExecutionChain handlerExecutionChain = requestMappingHandlerMapping.getHandler(request);
//            if (null != handlerExecutionChain) {
//                Object handler = handlerExecutionChain.getHandler();
//                if (handler instanceof HandlerMethod) {
//                    HandlerMethod handlerMethod = (HandlerMethod) handler;
//                    GetMapping noAuth = AnnotationUtils.getAnnotation(handlerMethod.getMethod(), GetMapping.class);
//                    if (null != noAuth) {
//                        filterChain.doFilter(request, response);
//                        return;
//                    }
//                }
//            }
//        } catch (Exception e) {
//            log.warn("", e);
//        }

        /**
         * 模拟过滤
         */
        if (requestURI.contains("filter")) {
            log.info("AuthFilter 过滤 requestURI is {}", requestURI);
            return;
        }
        filterChain.doFilter(request, response);
    }
}
